{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5ecef209-59d4-47aa-8826-4b48da6d1713",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0不能做除数\n"
     ]
    }
   ],
   "source": [
    "# 除SystemExit异常外，都可以被处理\n",
    "# 异常捕获 try-except-else-finally，尽量不用try嵌套但有些不可避免\n",
    "# 抛出异常用 raise\n",
    "num = 1\n",
    "num2 = 0\n",
    "try:\n",
    "    num / num2\n",
    "# 基类 BaseException，不建议直接继承，继承 Exception\n",
    "except ZeroDivisionError:\n",
    "    print(\"0不能做除数\")\n",
    "except Exception as e:\n",
    "    print(\"上一段程序有异常\")\n",
    "    print(e)\n",
    "else:\n",
    "    print(\"try代码无异常后，执行此代码\")\n",
    "finally: \n",
    "    print(\"try代码有/无异常，都会执行此代码\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "47628a61",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "value error !!!!",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[2], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\u001b[39m\"\u001b[39m\u001b[39mvalue error !!!!\u001b[39m\u001b[39m\"\u001b[39m)\n",
      "\u001b[1;31mValueError\u001b[0m: value error !!!!"
     ]
    }
   ],
   "source": [
    "raise ValueError(\"value error !!!!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "e3f92f09",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自定义异常\n",
    "class NameError(Exception):\n",
    "    def __init__(self, message):\n",
    "        self.message = message\n",
    "    \n",
    "    @property\n",
    "    def msg(self):\n",
    "        return f\"名字不允许使用 {self.message}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "952a2fab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "名字不允许使用 jerry\n"
     ]
    }
   ],
   "source": [
    "name = \"jerry\"\n",
    "try:\n",
    "    if name == \"jerry\":\n",
    "        raise NameError(name)\n",
    "\n",
    "except NameError as ne:\n",
    "    print(ne.msg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f1cf35a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "method\n"
     ]
    }
   ],
   "source": [
    "# 自定义 with 语句：with 语句使用 __enter__() 和 __exit__()两个方法实现\n",
    "class MyClass:\n",
    "    def __enter__(self):\n",
    "        # with 语句后的对象会被调用，并将结果返还给 as 语句后的对象\n",
    "        return self  # 返回实例本身\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        # with 语句块所有代码执行完，执行此部分代码\n",
    "        pass\n",
    "\n",
    "    def func(self):\n",
    "        print(\"method\")\n",
    "\n",
    "with MyClass() as mc:\n",
    "    mc.func()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
